package com.github.redis.controller;


import com.github.redis.config.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping(value = "/red")
public class RedpacketController {

    @Autowired
    private RedisTemplate redisTemplate;

    private final static String ID_KEY = "id:generator:redpacket";
    private final static String RED_PACKET_KEY = "redpacket:";
    private final static String RED_PACKET_CONSUME_KEY = "redpacket:consume:";


    /**
     * 抢红包
     *
     * @param redId
     * @param userId
     * @return
     */
    @GetMapping("/rob")
    public int rob(long redId, long userId){
        Object packet = this.redisTemplate.opsForHash().get(RED_PACKET_CONSUME_KEY + redId, String.valueOf(userId));
        if(packet == null){
            // 左边随机弹出一个
            Object obj = this.redisTemplate.opsForList().leftPop(RED_PACKET_KEY + redId);
            if(obj != null) {
                // 存入用户hash中
                this.redisTemplate.opsForHash().put(RED_PACKET_CONSUME_KEY + redId, String.valueOf(userId), obj);
                log.info("用户={}抢到={}", userId, redId);
                // TODO 异步将数据同步到数据库
                return (Integer) obj;
            }
            // 已抢完
            return -1;
        }
        // 已枪
        return -2;
    }

    /**
     */
    @GetMapping(value = "/set")
    public long find(int total, int count) {
        // 拆解红包
        Integer[] packet = this.splitRedPacket(total, count);
        long n = this.incrementId();
        String key = RED_PACKET_KEY + n;
        this.redisTemplate.opsForList().leftPushAll(key, packet);
        // 设置三天过期
        this.redisTemplate.expire(key, 3, TimeUnit.DAYS);
        log.info("拆解红包{}={}", key, packet);
        return n;
    }

    public long incrementId(){
        long n = this.redisTemplate.opsForValue().increment(ID_KEY);
        return n;
    }

    /**
     * 红包金额拆分
     * @param total
     * @param count
     * @return
     */
    private Integer[] splitRedPacket(int total, int count){
        int use = 0;
        Integer[] array = new Integer[count];
        Random random = new Random();
        for (int i = 0; i < count; i++) {
            if(i == count - 1) {
                array[i] = total - use;
            } else {
                // 红包金额浮动系数
                int avg = (total - use) * 2 / (count - i);
                array[i] = 1 + random.nextInt(avg - 1);
            }
            use = use + array[i];
        }
        return array;
    }
}












